﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using System.Text;

namespace EMS.Calendar.Helpers {
    public static class CheckBoxListHelper {
        /// <summary>
        /// Builds a CheckBoxList with selected items.
        /// Source: http://www.codekeep.net/snippets/7bd90b77-b6c7-43db-988f-b1389a64a157.aspx
        /// </summary>
        /// <param name="Name">Used in to name the collection of checkboxes</param>
        /// <param name="items">List<ListItems> items you want selected</param>
        /// <returns>Html</returns>
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> items) {
            return CheckBoxList(helper, name, items, null);
        }

        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> items, IDictionary<string, object> checkboxHtmlAttributes) {
            StringBuilder output = new StringBuilder();

            foreach (var item in items) {
                output.Append("<div class=\"fields\"><label>");
                var checkboxList = new TagBuilder("input");
                checkboxList.MergeAttribute("type", "checkbox");
                checkboxList.MergeAttribute("name", name);
                checkboxList.MergeAttribute("value", item.Value);

                // Check to see if it's checked
                if (item.Selected)
                    checkboxList.MergeAttribute("checked", "checked");

                // Add any attributes
                if (checkboxHtmlAttributes != null)
                    checkboxList.MergeAttributes(checkboxHtmlAttributes);

                checkboxList.SetInnerText(item.Text);
                output.Append(checkboxList.ToString(TagRenderMode.SelfClosing));
                output.Append("&nbsp; " + item.Text + "</label></div>");
            }

            return MvcHtmlString.Create(output.ToString());
        } 
    }
}